package org.cloudlab.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.cloudlab.bean.SubRecord;
import org.cloudlab.common.ResponseResult;
import org.cloudlab.service.ISubRecordService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 投稿记录控制器
 *
 * @author Liu Yicong
 * @date 2023/9/8
 */
@CrossOrigin
@RestController
@RequestMapping(value = "record")
public class SubRecordController {

	private static final Logger logger = LoggerFactory.getLogger(SubRecordController.class);

	@Autowired
	private ISubRecordService subRecordService;

	/**
	 * 通过用户id来查找该用户的所有投稿记录
	 */
	@GetMapping("queryByUserId")
	public ResponseResult<Page<SubRecord>> queryByPage(Page<SubRecord> page, String onlyOwn, String paperName) {
		Page<SubRecord> list;
		try {
			list = subRecordService.queryByPage(page, onlyOwn, paperName);
		} catch (Exception e) {
			logger.error("Exception=======>", e);
			return ResponseResult.fail("查询失败, 请检查文章是否存在", null);
		}
		return ResponseResult.success("查询成功", list);
	}


	/**
	 * 通过文章id查询所有该文章的投稿记录
	 *
	 * @param paperId 文章id
	 */
	@GetMapping("queryByPaperId")
	public ResponseResult<Page<SubRecord>> queryByPaperId(Page<SubRecord> page, Long paperId) {
		Page<SubRecord> list;
		try {
			list = subRecordService.queryByPaperId(page, paperId);
		} catch (Exception e) {
			logger.error("Exception=======>", e);
			return ResponseResult.fail("查询失败, 请检查文章是否存在", null);
		}
		return ResponseResult.success("查询成功", list);
	}


	@GetMapping("queryByJournalId")
	public ResponseResult<Page<SubRecord>> queryByJournalId(Page<SubRecord> page, Long journalId) {
		Page<SubRecord> list;
		try {
			list = subRecordService.queryByJournalId(page, journalId);
		} catch (Exception e) {
			logger.error("Exception=======>", e);
			return ResponseResult.fail("查询失败, 请检查文章是否存在", null);
		}
		return ResponseResult.success("查询成功", list);
	}


	/**
	 * 添加投稿记录
	 */
	@PostMapping("add")
	public ResponseResult<String> add(@RequestBody SubRecord subRecord) {
		try {
			subRecordService.add(subRecord);
		} catch (Exception e) {
			logger.error("Exception=======>", e);
			return ResponseResult.fail(e.getMessage(), null);
		}

		return ResponseResult.success();
	}

	/**
	 * 更新投稿记录
	 */
	@PostMapping("update")
	public ResponseResult<String> update(@RequestBody SubRecord subRecord) {
		try {
			subRecordService.update(subRecord);
		} catch (Exception e) {
			logger.error("Exception=======>", e);
			return ResponseResult.fail(e.getMessage(), null);
		}

		return ResponseResult.success();
	}

	/**
	 * 删除投稿记录
	 */
	@GetMapping("remove")
	public ResponseResult<String> remove(Long subRecordId) {
		try {
			subRecordService.deleteBySubRecordId(subRecordId);
		} catch (Exception e) {
			logger.error("Exception=======>", e);
			return ResponseResult.fail(e.getMessage(), null);
		}
		return ResponseResult.success();
	}

}
